package org.example.binding;

import org.example.builder.MapperAnnotationBuilder;
import org.example.config.Configuration;
import org.example.session.SqlSession;

import java.util.HashMap;
import java.util.Map;

public class MapperRegistry {
    private final Configuration configuration;

    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }


    public void addMapper(Class<?> boundType) {
        this.knownMappers.put(boundType,new MapperProxyFactory<>(boundType));
        //MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        //parser.parse();
    }
}
